<template>
  <div class="type-container">
    <van-sidebar v-model="currentSidebar" @change="sidebarOnChange">
      <van-sidebar-item
        :title="item.name"
        v-for="item in state.typeItems"
        :key="item.id"
      />
    </van-sidebar>
    <!-- v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad" -->
    <van-empty
      description="暂无更多数据"
      v-if="!state.childrenTypeItems?.length"
    />

    <van-list class="type-list" v-else>
      <van-cell
        v-for="item in state.childrenTypeItems"
        :key="item.id"
        :title="item.name"
      >
        <template #right-icon>
          <van-space fill>
            <van-icon name="edit" @click="typeOnEdit(item)" />
            <van-icon name="delete-o" @click="typeOnDelete(item)" />
          </van-space>
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<script setup>
import CustomTreeSelect from "@/components/CustomTreeSelect/Index.vue";
import { showSuccessToast } from "vant";
import { reactive, ref } from "vue";
import { useAppStore } from "../../../stores";
import { getBookTypeListForTree, deleteBookType } from "@/service/book";
import { useRoute, useRouter } from "vue-router";
import { Toast } from "vant";

const appStore = useAppStore();
const router = useRouter();
const route = useRoute();

appStore.setAppNav("navTitle", "图书类别");
appStore.setAppNav("navRightText", "新增");
appStore.setAppNav("navRightClick", () => {
  router.push({
    name: "libraryTypeCreate",
    query: {
      model: route.query.model,
    },
  });
});

const activeId = ref(1);
const activeIndex = ref(0);
const state = reactive({
  typeItems: [],
  childrenTypeItems: [],
});

const currentSidebar = ref(null); //当前选中的父级菜单
const sidebarOnChange = (index) => {
  state.childrenTypeItems = state.typeItems[index].list;
};

const getBookTypeTree = async () => {
  const { data } = await getBookTypeListForTree({
    type: route.query.model,
  });
  state.typeItems = data;
  state.childrenTypeItems = data[0]?.list;
};

const typeOnEdit = (item) => {
  router.push({
    name: "libraryTypeEdit",
  });
};

const typeOnDelete = async (item) => {
  const { data } = await deleteBookType(item);
  if (data === 1) {
    showSuccessToast("删除成功！");
    getBookTypeTree();
  }
};

getBookTypeTree();
</script>

<style scoped lang="less">
.type-container {
  display: flex;

  .type-list {
    flex: 1;
  }
}
</style>
